package xin.marcher.module.quality.mq.consumer.listener;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.marcher.module.common.constants.RocketDelayedLevel;
import xin.marcher.module.common.enums.message.BinlogType;
import xin.marcher.module.common.enums.quality.ProblemTypeEnum;
import xin.marcher.module.common.enums.quality.QualityAuditStatusEnum;
import xin.marcher.module.common.enums.quality.SurveyStatusEnum;
import xin.marcher.module.common.exception.BaseBizException;
import xin.marcher.module.common.exception.ProductErrorCodeEnum;
import xin.marcher.module.common.message.DataChangeMessage;
import xin.marcher.module.common.utils.DateFormatUtil;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.quality.domain.entity.ItemQualityControlSurveyTaskDO;
import xin.marcher.module.quality.mq.producer.DefaultProducer;
import xin.marcher.module.quality.repository.SurveyRepository;

import java.util.List;
import java.util.Objects;

import static xin.marcher.module.common.constants.quality.SurveyTaskChangedColumnConstants.AUDIT_STATUS;
import static xin.marcher.module.common.constants.quality.SurveyTaskChangedColumnConstants.SURVEY_STATUS;

/**
 *
 */
@Slf4j
@Component
public class SurveyFormSendListener implements MessageListenerConcurrently {
    @Autowired
    private SurveyRepository surveyRepository;

    @Autowired
    private DefaultProducer defaultProducer;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                log.info("调查单资质证明上传通知消息，消息内容：{}", messageExt.getBody());
                String msg = new String(messageExt.getBody());

                DataChangeMessage tableDataChangeMessage = JsonUtil.json2Object(msg, DataChangeMessage.class);
                if (Objects.isNull(tableDataChangeMessage)) {
                    throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
                }

                List<String> updateColumns = tableDataChangeMessage.getUpdateColumns();

                if (tableDataChangeMessage.getAction().equals(BinlogType.UPDATE.getValue())
                        && CollectionUtils.isNotEmpty(updateColumns)) {
                    // 判断变更字段，如果变更字段是survey_status，则执行《第一次发送调查单》推送消息的逻辑
                    // 具体逻辑需要对状态值进行判断
                    if (updateColumns.contains(SURVEY_STATUS)) {
                        Integer surveyId = getSurveyId(tableDataChangeMessage);

                        ItemQualityControlSurveyTaskDO surveyTaskDO = surveyRepository.querySurveyTask(surveyId);
                        if (SurveyStatusEnum.SURVEY_FORM_SEND_STATUS.getCode().equals(surveyTaskDO.getSurveyStatus())) {
                            informByPush(surveyTaskDO);
                        }
                    }
                    // 如果变更字段是audit_status，则《重新发送调查单》推送消息的逻辑
                    if (updateColumns.contains(AUDIT_STATUS)) {
                        Integer surveyId = getSurveyId(tableDataChangeMessage);
                        ItemQualityControlSurveyTaskDO surveyTaskDO = surveyRepository.querySurveyTask(surveyId);
                        if (QualityAuditStatusEnum.ADDITIONAL.getCode().equals(surveyTaskDO.getAuditStatus())) {
                            informByPush(surveyTaskDO);
                        }
                    }
                }

                // 发送回调消息
                defaultProducer.sendMessage(tableDataChangeMessage.getCallbackTopic(),
                        tableDataChangeMessage.getMessageNo(), RocketDelayedLevel.DELAYED_1m, "表变更消息处理完成返回延迟消息");

            }
        } catch (Exception e) {
            log.error("consume error, 消费考核结果失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }

        return null;
    }

    /**
     * 拿到id
     *
     * @param tableDataChangeMessage
     * @return
     */
    private Integer getSurveyId(DataChangeMessage tableDataChangeMessage) {
        Object keyId = tableDataChangeMessage.getKeyId();
        if (Objects.isNull(keyId)) {
            throw new BaseBizException(ProductErrorCodeEnum.PARAM_CHECK_ERROR, ProductErrorCodeEnum.PARAM_CHECK_ERROR.getErrorCode());
        }
        return Integer.valueOf(keyId.toString());
    }

    /**
     * 第三方平台推送消息到运营
     * (此处模拟推送消息服务，消息平台业务商品侧不实现)
     *
     * @param surveyTaskDO
     */
    private void informByPush(ItemQualityControlSurveyTaskDO surveyTaskDO) {
        String messageBody = "您的商品存在"
                + "质量问题:" + ProblemTypeEnum.getByCode(surveyTaskDO.getProblemType()).getValue()
                + "请于:" + DateFormatUtil.format(surveyTaskDO.getDeadline()) + "前上传证明材料！";
        log.info("消息推送中：消息内容：{}", messageBody);
    }
}
